const fs = require('fs');

const TIME_Test = 'run test';
const RootDir = './mk';

console.time(TIME_Test);

const tab1Data = JSON.parse(fs.readFileSync('./tab1_data.json', { encoding:'utf-8' }).toString());

const catalogues = tab1Data.grid_menu.map(menu=>{
    return { title:menu.key, list:[] };
});

const createJsonData = (file) => {
    let text = fs.readFileSync(RootDir+'/'+file, { encoding:'utf-8' }).toString();
    
    let data = {
        title:'',
        note:'',
        list:[]
    };
    let lines = text.split('\r\n');
    for(let i=0; i<lines.length; i++){
        let line = lines[i].trim();
        let hn = line.match(/^(#+)\s+((.?)+)$/);
        if (hn) {
            if(hn[1].length==1){
                data.title = hn[2];
                line = lines[i+1];
                if (line.length>0) {
                    data.note = line;
                    i++;
                }
                continue;
            }
            else if(hn[1].length==2){
                let item = {
                    title:hn[2],

                };
                data.list.push(item);
                line = lines[++i];
                if (line!=undefined && line.length>0) {    
                    let formatText = (text) => text.replace(/，|\s+|、|;/g,',').replace(/＝/g,'=').replace(/（/g,'(').replace(/）/g,')').replace(/．/g,'.').replace(/～/g,'~');
                    if (line.indexOf('|')>=0) {
                        let header = line.replace(/^|/,'').split('|');
                        item.type = 'inputs';
                        item.labels = [];
                        item.answer = [];
                        i++;
                        do{
                            i++;
                            line = lines[i];
                            if (line==undefined || line.indexOf('|')<0) break;
                            let cols = line.replace(/^|/,'').split('|');
                            for(let c=0; c<cols.length; c++){
                                let col = cols[c].trim();
                                if (c==0) {
                                    item.labels.push(header[c].trim()+col);
                                }else if (c==1) {
                                    item.labels[item.labels.length-1]+='，'+header[c].trim();
                                    item.answer.push(formatText(col));
                                }else{
                                    item.labels.push(header[c].trim());
                                    item.answer.push(formatText(col));
                                }
                            }
                        }while(i<lines.length);
                    } else {
                        let m = line.match(/^\-\s\[(\s|x)\]\s((.?)+)$/);
                        if (m) {
                            item.select=[m[2]];
                            if(m[1]=='x') item.answer=0;
                            let j=i;
                            do{
                                line = lines[++i];
                                if (line==undefined || line.length<1) break;
                                m = line.match(/^\-\s\[(\s|x)\]\s((.?)+)$/);
                                if (!m) break;
                                item.select.push(m[2]);
                                if(m[1]=='x'){
                                    let index = i-j;
                                    if(item.answer==undefined) {
                                        item.answer=index;
                                    }else if(Array.isArray(item.answer)){
                                        item.answer.push(index);
                                    }else{
                                        item.answer=[item.answer,index];
                                    }
                                }
                            }while (i<lines.length);
                            if(Array.isArray(item.answer)) item.type='checkbox';
                            else item.type='radio';
                            i--;
                        } else {
                            m = line.match(/`([^`])+`/g);
                            if (!m) {
                                item.type = 'input';
                                item.answer = formatText(line);
                            }else{
                                item.type = 'inputs';
                                item.answer = [];
                                item.labels = [];
                                for(let j=0; j<m.length; j++){
                                    item.answer.push(formatText(m[j].substring(1, m[j].length-1)));
                                    let l = line.indexOf(m[j]);
                                    if (l>=0) {
                                        let label = line.substring(0,l);
                                        item.labels.push(label);
                                        line = line.substring(l+m[j].length);
                                    }
                                }
                                if (line.length>0) {
                                    item.labels.push(line);
                                }
                            }
                        }
                    }
                    let toasts = [];
                    do{
                        line = lines[++i];
                        if (line==undefined) break;
                        let m2 = line.match(/^\-\s+((.?)+)$/);
                        if (!m2) break;
                        toasts.push(m2[1]);
                    }while(i<lines.length);
                    if (toasts.length>0) item.toasts = toasts;
                }
            }
        }
    }

    
    console.log('log',{ file, data:data.list[0] });
    return data;
};

const mks = fs.readdirSync(RootDir);
mks.forEach((mk,i)=>{
    if(!mk.endsWith('.md')) return;
    // if(i!=1) return;
    let dirs = mk.replace('.md','').split('_');
    let cata = catalogues.find(cata=>cata.title==dirs[0]);
    if (!cata) return;

    let name;
    if (dirs.length<2) throw Error('file format is error');
    else  {
        for(let i=1; i<dirs.length; i++){       
            if (i==1) name = dirs[i];
            else name += '_'+dirs[i];
        }
    }
    let data = createJsonData(mk);
    
    let subject = cata.list.find(m=>m.value==name);
    if (subject) throw Error('file subject is exitis');
    subject = {
        title:data.title,
        note:data.note,
        value:name
    };
    cata.list.push(subject);
    try{
        fs.accessSync(dirs[0]);
    }catch(e){
        fs.mkdirSync(dirs[0]);
    }
    //对象转化成json串的精简版本
    let oText = JSON.stringify(data,null,'\t');
    fs.writeFileSync(`./${dirs[0]}/subject_${name}.json`, oText, { encoding:'utf-8' });
});
catalogues.forEach((cata)=>{
    let oText = JSON.stringify(cata,null,'\t');
    fs.writeFileSync(`./catalogue_${cata.title}.json`, oText, { encoding:'utf8' });
});
// console.log('log',{ mks });

console.timeEnd(TIME_Test);